package com.youcan.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author LiChao E-mail:what_is_javascript@163.com
 * @date:2012-8-25 上午11:32:18
 * @version :V1.0
 *
 */

/**
 * 总拦截器
 * 
 * preHandle调用controller具体方法之前调用， postHandle完成具体方法之后调用，
 * afterCompletion完成对页面的render以后调用
 * 
 */
public class YCInterceptor implements HandlerInterceptor {

	private long beginTime = 0L;
	private long endTime = 0L;

	/**
	 * afterCompletion 最后执行，可用于释放资源 参数中的Object handler是下一个拦截器。
	 * 可以根据ex是否为null判断是否发生了异常，进行日志记录
	 */
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception exception)
			throws Exception {
		// TODO Auto-generated method stub
		endTime = System.currentTimeMillis();
		System.out.println("方法调用耗时:" + (endTime - beginTime) / 1000.0 + "秒.");
	}

	/**
	 * postHandle 可以修改业务及视图
	 */
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	/**
	 * preHandle 可以进行编码、安全控制等处理
	 */
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		System.out.println("编码：" + request.getCharacterEncoding());
		if (request.getCharacterEncoding() == null) {
			request.setCharacterEncoding("UTF-8");
		}

		beginTime = System.currentTimeMillis();
		// TODO Auto-generated method stub
		// response.sendRedirect("xtwh.html");
		return true;
	}

}
